package com.acme.bankapp.service.bank.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * This class represents client which send request to {@link BankServer} object
 *
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class BankClient {
    private final static int PORT = 12345;
    private final static String LOCAL_HOST = "127.0.0.1";

    private void sendMessage(final PrintWriter out, final String message) {
        out.println(message);
        System.out.println("client ==> " + "'" + message + "'");
    }

    private void processConsoleInput(final BufferedReader in, final PrintWriter out) {
        String consoleInput;
        try (BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
            while ((consoleInput = stdIn.readLine()) != null) {
                sendMessage(out, consoleInput);
                String reply = in.readLine();
                System.out.println("'" + reply + "' <== server");
                if ("close".equals(reply)) {
                    break;
                }
            }
        } catch (IOException ioException) {
            ioException.getStackTrace();
            System.err.println(ioException.getMessage());
        }
    }

    /**
     * This method starts client
     */
    public void run() {
        try (Socket socket = new Socket(LOCAL_HOST, PORT);
             PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {

            System.out.println("Connected to " + LOCAL_HOST + " in port " + PORT);
            String salutation = input.readLine();
            System.out.println("'" + salutation + "' <== salutation from server");
            processConsoleInput(input, output);

        } catch (UnknownHostException unknownHostException) {
            unknownHostException.printStackTrace();
            System.err.println("Connection to unknown host failed");
        } catch (IOException ioException) {
            ioException.printStackTrace();
            System.err.println(ioException.getMessage());
        } catch (NullPointerException nullPointerException) {
            nullPointerException.printStackTrace();
            System.err.println(nullPointerException.getMessage());
        }
    }

}
